const codeRecord = require('../models/codeRecord')

var express = require('express');
var router = express.Router();

var formidable = require('formidable');

router.post('/', (req, res) => {
    var form = new formidable.IncomingForm();
    form.parse(req, async (err, fields) => {
        if(err) {
            res.json({'state': false, 'msg': err});
        }else {
            var user_num = function(time_s, time_e) {
                return new Promise((resolve, reject) => {
                    codeRecord.aggregate([
                        {$unwind: '$codeRecord_list'},
                        {$match: {'codeRecord_list.content.time': {$gte: time_s, $lte: time_e}}},
                        {$group: {'_id': {'user': '$codeRecord_list.content.user'}, 'content': {$sum: 1}}}
                    ], (err, results) => {
                        if(err) {
                            res.json({'state': false, 'msg': err})
                        }else {
                            resolve(results.length);
                        }
                    })
                })
            }
            var time_s = new Date(new Date(fields.time).setDate(1));
            time_s.setHours(0);
            time_s.setMinutes(0);
            time_s.setSeconds(0);
            time_s.setMilliseconds(0);
            time_s = new Date(time_s);
            var time_e = new Date(time_s);
            time_e.setMonth(time_e.getMonth()+1);
            var num = Math.round((time_e-time_s)/(24*60*60*1000));
            var time_interval = [new Date(time_s)];
            for(let i=0;i<num;i++) {
                var time_t = new Date(time_s.setDate(time_s.getDate()+1))
                time_interval.push(time_t);
            }
            var numByDay = [];
            for(let j=1;j<time_interval.length;j++) {
                let num = await user_num(time_interval[j-1].getTime(), time_interval[j].getTime());
                let data = {
                    "time": j,
                    "num": num
                }
                numByDay.push(data);
            }
            res.json({
                'state': true,
                'month':`${new Date(fields.time).getFullYear()}年${new Date(fields.time).getMonth()+1}月`,
                'numByDay': numByDay
            });
        }
    });
})

module.exports = router;